#include "ProtoTd.h"
#include "../net/NetMsg.h"
#include "../lua/LuaRegister.h"
#include "../net/NetConfig.h"
#include "../net/MessageDispatch.h"

NetMsg* ProtoTd::pack_protocol(lua_State* lua, int index)
{
	if (!lua_isstring(lua, index)) {
		return nullptr;
	}
	std::string msg = lua_tostring(lua, index);
	auto proto = NetConfig::instance()->getConfig().get_proto_by_name(msg);
	if (!proto) {
		return nullptr;
	}
	std::vector<td_proto::Values> values;
	bool success = MessageDispatch::instance()->lua_convert_value(values, lua, index + 1 , proto->args);
	if (!success)
	{
		char error_message[200];
		sprintf(error_message, "send_to_port pack message(%s) fail!\n", msg.c_str());
		luaL_argerror(lua, 3, error_message);
		return nullptr;
	}
	NetMsg* bbos = new NetMsg;
	success = td_proto::encode_proto(*bbos, NetConfig::instance()->getConfig(), msg, values);
	if (!success) {
		delete bbos;
		return nullptr;
	}
	bbos->endSendMsg();
	return bbos;
}

int ProtoTd::unpack_protocol(lua_State* lua, NetMsg* msg)
{
	if (!msg) {
		return 0;
	}
	bool success = MessageDispatch::instance()->unpackBuffer(lua, msg);
	if (!success) {
		lua_pushnil(lua);
		lua_pushnil(lua);
	}
	return 2;
}
